/*
 * Copyright 2016 drakeet. https://github.com/drakeet
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.epfresh.adapter;

import android.content.Intent;
import android.graphics.Paint;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.activity.DetailGoodsActivity;
import com.epfresh.activity.HomeSecondAreaActivity;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.bean.CountDownTime;
import com.epfresh.bean.HomeCommTag;
import com.epfresh.bean.HomeTop;
import com.epfresh.bean.HomeTopBean;
import com.epfresh.views.HomeCountDownView;
import com.epfresh.views.tag.TagCloudView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import multitype.ItemViewBinder;


public class ViewBinderHomeSecondOnlyOne
    extends ItemViewBinder<HomeTopBean.SecondsOne, ViewBinderHomeSecondOnlyOne.ViewHolder> implements View.OnClickListener{
    HomeCountDownView.OnCountDownListener countDownListener;

    public HomeCountDownView.OnCountDownListener getCountDownListener() {
        return countDownListener;
    }

    public void setCountDownListener(HomeCountDownView.OnCountDownListener countDownListener) {
        this.countDownListener = countDownListener;
    }

    @Override
    public void onClick(View v) {
        Object tag = v.getTag(R.id.item_key_status);
        if(tag!=null && tag instanceof HomeTop.SeckillBeanX.SeckillBean) {
            Intent more_activity = new Intent(v.getContext(),
                    HomeSecondAreaActivity.class);
            v.getContext().startActivity(more_activity);
        }else{
            if (tag instanceof HomeTop.SeckillBeanX.SeckillBean.SeckillListBean) {
                HomeTop.SeckillBeanX.SeckillBean.SeckillListBean bean = (HomeTop.SeckillBeanX.SeckillBean.SeckillListBean) tag;
                Intent commIntent = new Intent(v.getContext(), DetailGoodsActivity.class);
                commIntent.putExtra("id", bean.getProduct().getId());
                commIntent.putExtra("storeId", bean.getProduct().getStoreId());
                commIntent.putExtra("image_url", bean.getProduct().getThumbnail());
                commIntent.putExtra("promotionItemId", bean.getPromotionItemId());
                commIntent.putExtra("title", bean.getProduct().getTitle());
                v.getContext().startActivity(commIntent);
            }
        }
    }
    @NonNull @Override
    protected ViewHolder onCreateViewHolder(
        @NonNull LayoutInflater inflater, @NonNull ViewGroup parent) {
        View view = inflater.inflate(R.layout.view_home_second_one, parent, false);
        return new ViewHolder(view);
    }

    CountDownTime cdt;

    @Override
    protected void onBindViewHolder(@NonNull ViewHolder holder, @NonNull HomeTopBean.SecondsOne post) {
        HomeTop.SeckillBeanX.SeckillBean postList = post.goods;
        if(postList.getSeckillList() == null || postList.getSeckillList().size() == 0)
            return;
        cdt = new CountDownTime();
        cdt.setStartSubTime(postList.getBeginTime());//fineRecommendation.getString("beginTime"));
        cdt.setEndSubTime(postList.getEndTime());//fineRecommendation.getString("endTime"));
        cdt.setSysDate(postList.getSysDate());//fineRecommendation.getString("sysDate"));
        cdt.init();
        holder.cdv.setOnCountDownListener(countDownListener);
        long countDownTime = cdt.getCountDownTime();
        if (countDownTime == 0) {//活动已经结束
            holder.tv_second_hint.setVisibility(View.INVISIBLE);
        } else if (countDownTime > 0) {//活动进行中
            holder.cdv.showTimer(cdt, countDownTime, 1000);
            holder.tv_second_hint.setVisibility(View.INVISIBLE);
            //holder.tv_second_hint.setText("先下单先得哦");
        } else if (countDownTime < 0) {
            holder.cdv.showTimer(cdt, countDownTime, 1000);
            holder.tv_second_hint.setVisibility(View.VISIBLE);
            initSecKillHint(postList.getBeginTime(), postList.getSysDate(),holder.tv_second_hint);
        }
        holder.itemView.setTag(R.id.item_key_status,postList);
        holder.itemView.setOnClickListener(this);

        HomeTop.SeckillBeanX.SeckillBean.SeckillListBean bean  = postList.getSeckillList().get(0);
        if(bean==null||bean.getProduct()==null)
            return;
        holder.tv_price.setText(""+bean.getPrice()+"元/"+bean.getProduct().getChargeUnit());
        holder.tv_old_price.setText(bean.getProduct().getPriceUnit());
        holder.tv_old_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        holder.tv_title.setText(bean.getProduct().getProductParseDto().getTitle());

        Log.e("title", holder.tv_title.getText()+"");

        ImageLoader.getInstance().displayImage(bean.getProduct().getThumbnail(), holder.iv_product);
        if (bean.getPromotionMarkUrl() != null && !bean.getPromotionMarkUrl().equals("") && !bean.getPromotionMarkUrl().equals("null"))
            ImageLoader.getInstance().displayImage(bean.getPromotionMarkUrl(), holder.iv_tag);
        else
            holder.iv_tag.setVisibility(View.INVISIBLE);

        holder.rl_item.setTag(R.id.item_key_status,bean);
        holder.rl_item.setOnClickListener(this);


        holder.tv_package.setText(bean.getProduct().getPack());

        if (bean.getStatus() != null && "2".equals(bean.getStatus()))
            holder.tv_finish_flag.setVisibility(View.GONE);
        else if ("1".equals(bean.getStatus())) {
            holder.tv_finish_flag.setVisibility(View.VISIBLE);
            holder.tv_finish_flag.setText("即将开始");
        } else if ("3".equals(bean.getStatus())) {
            holder.tv_finish_flag.setVisibility(View.VISIBLE);
            holder.tv_finish_flag.setText("结束了");
        } else {
            holder.tv_finish_flag.setVisibility(View.VISIBLE);
            holder.tv_finish_flag.setText("抢光了");
        }

        ArrayList<HomeCommTag> tags = bean.getProduct().getTags();
        if (tags != null && tags.size() > 0) {
            holder.tag.setVisibility(View.VISIBLE);
        } else {
            holder.tag.setVisibility(View.GONE);
        }
        holder.tag.setCommTags(tags);

        if(bean.getQuantityPerAccount()!=null&&bean.getQuantityPerAccount()!=0){
            holder.tv_promotion_limit.setVisibility(View.VISIBLE);
            holder.tv_promotion_limit.setText("限购"+bean.getQuantityPerAccount()+bean.getProduct().getChargeUnit());
        }else{
            holder.tv_promotion_limit.setVisibility(View.GONE);
        }
    }

    static final class ViewHolder extends RecyclerView.ViewHolder {

        //private RecyclerView recyclerView;
        //private ViewBinderHomeSecondItemAdapter adapter;
        private TextView tv_second_hint;
        private HomeCountDownView cdv;
        ImageView iv_product,iv_tag;//iv_type;title + drawable? 预售？
        TextView tv_title,tv_package,tv_price,tv_old_price,tv_finish_flag,tv_promotion_limit;
        TagCloudView tag;
        View rl_item;
        ViewHolder(@NonNull View itemView) {
            super(itemView);
            rl_item = itemView.findViewById(R.id.rl_item);
            iv_product = (ImageView) itemView.findViewById(R.id.iv_product);
            iv_tag = (ImageView) itemView.findViewById(R.id.iv_tag);
            tv_title = (TextView) itemView.findViewById(R.id.tv_title_);
            tv_package = (TextView) itemView.findViewById(R.id.tv_package);
            tv_price = (TextView) itemView.findViewById(R.id.tv_price);
            tv_old_price = (TextView) itemView.findViewById(R.id.tv_old_price);
            tv_finish_flag = (TextView) itemView.findViewById(R.id.tv_finish_flag);
            tv_promotion_limit = (TextView) itemView.findViewById(R.id.tv_promotion_limit);
            tag = (TagCloudView) itemView.findViewById(R.id.ll_tags);

            tv_second_hint = (TextView) itemView.findViewById(R.id.tv_second_hint);
            cdv = (HomeCountDownView) itemView.findViewById(R.id.cdv);
        }
    }

    void initSecKillHint(String beginTime, String nowTime,TextView tv_second_hint) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Calendar today = Calendar.getInstance();
            Calendar target = Calendar.getInstance();
            today.setTime(sdf.parse(nowTime));
            today.set(Calendar.HOUR_OF_DAY, 0);
            today.set(Calendar.MINUTE, 0);
            today.set(Calendar.SECOND, 0);

            target.setTime(sdf.parse(beginTime));
            target.set(Calendar.HOUR_OF_DAY, 0);
            target.set(Calendar.MINUTE, 0);
            target.set(Calendar.SECOND, 0);

            long intervalMilli = target.getTimeInMillis() - today.getTimeInMillis();
            int xcts = (int) (intervalMilli / (24 * 60 * 60 * 1000));
            if (xcts == 0) {
                tv_second_hint.setText("今天" + beginTime.substring(11, 16) + "开抢");
            } else if (xcts == 1) {
                tv_second_hint.setText("明天" + beginTime.substring(11, 16) + "开抢");
            } else {
                tv_second_hint.setText("后天" + beginTime.substring(11, 16) + "开抢");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
